import json
import threading
from queue import Queue

from ..center.recv import MQRecvMessage
from ..center.send import MQSendMessage
from ...configread import MyConfigParser
from ...mprocesspoll.MThreadingRun import MThreadingRun

WorkerThreadNumber = 10
GlobalQueueDistribute = Queue(WorkerThreadNumber * 10)  # 分发
GlobalQueueCollect = Queue(WorkerThreadNumber * 10)  # 汇总


class Distributer(MQRecvMessage, threading.Thread):
    """
    从mq接受信息过来
    """

    def __init__(self, cofig, queuetest, number):
        print('Distributer __init__ ...')
        super().__init__(cofig, queuetest)
        threading.Thread.__init__(self)
        self.config = cofig
        self.queuetest = queuetest
        self.GolobalConfig = {}
        self.number = number
        self.qos()
        # self.read_config()

    def qos(self, prefetch_count=1):
        super().qos(prefetch_count=self.number)

    def read_config(self):
        self.GolobalConfig = MyConfigParser(self.config).get_configparser().set_keep_keys_case().get_cf()

    def start(self):
        threading.Thread.start(self)

    def run(self):
        while True:
            if not self.ConnRabbitMQ.is_open:
                self.ConnRabbitMQ = self.OpenConn()
                self.qos()
            method, properties, body = self.basic_get()
            if not body:
                print('GlobalQueueDistribute.qsize: %d' % GlobalQueueDistribute.qsize())
                print('GlobalQueueCollect.qsize: %d' % GlobalQueueCollect.qsize())
                duration = 10
                print('not body, Distributer thread will sleep %ds ...' % duration)
                self.ConnRabbitMQ.sleep(duration)
                continue

            task = body.decode('utf-8')
            print('recv body: %s' % task)
            print('GlobalQueueDistribute.qsize: %d' % GlobalQueueDistribute.qsize())
            GlobalQueueDistribute.put(task)
            self.channel.basic_ack(delivery_tag=method.delivery_tag)


class dealThread(MThreadingRun):

    def __init__(self, num):
        super(dealThread, self).__init__(num)
        
    def getTask(self, *args, **kwargs):
        pass

    def setTask(self,results=None, *args, **kwargs):
        while not GlobalQueueDistribute.empty():
            result = GlobalQueueDistribute.get()
            args, kwargs = self.parameters(result)
            self.add_job(self.func, *args, **kwargs)

    def parameters(self, result):
        """
        这里需要重写
        :param result:
        :return:
        """
        dic = json.loads(result)
        return [], {}

    def dealresult(self, *args, **kwargs):
        for sql in self.results:
            GlobalQueueCollect.put(sql)


# 汇总任务处理状态，发送 sql 语句回 center
class Collecter(MQSendMessage, threading.Thread):
    def __init__(self, cofig, queuetest):
        print('Collecter __init__ ...')
        super().__init__(cofig, queuetest)
        threading.Thread.__init__(self)
        self.config = cofig
        self.queuetest = queuetest

    def run(self):
        while True:
            sql = GlobalQueueCollect.get()
            if not self.ConnRabbitMQ.is_open:
                self.ConnRabbitMQ = self.OpenConn()
            try:
                self.publish(sql)
                print('GlobalQueueCollect.qsize: %d' % GlobalQueueCollect.qsize())
            except:
                print('reconnect for ConnectionClosed')
                self.ConnRabbitMQ = self.OpenConn()
                self.channel.basic_publish(sql)

            print('send message: %s' % sql)
